import { NextResponse } from "next/server";
import { PostService, UserService } from "@/utils/prisma";


export async function POST(request: Request) {

    const user = request.headers.get('user') as any;
    const { id } = JSON.parse(user)

    const { action, params } = await request.json();

    try {
        switch (action) {
            case "init": {
                // const { bookall } = params
                const collect = await PostService.getUserCollect(id);
                const myCollect = await PostService.getPostsByAuthor(id)

                if (collect || myCollect) {
                    return NextResponse.json({ data: { collect: collect, myCollect: myCollect }, status: 200 });
                } else {
                    return NextResponse.json({ data: [], status: 200 });
                }

            }
            case "read": {

                try {
                    // PostService.createPost("Pigs is Pigs", out, "all")
                    return NextResponse.json({
                        data: [],
                        status: 200,
                    })
                } catch (e) {
                    // console.log(e, 894);
                    return NextResponse.json({
                        status: 500,
                        error: "Failed to process request",
                    });
                }

            }
            case "add": {
                //添加收藏
                const { bookId } = params
                const book = await UserService.collectBook(id, bookId)
                if (book) {
                    return NextResponse.json({ data: [], status: 200, message: "success" });
                } else {
                    return NextResponse.json({ data: [], status: 200, message: "fail" });
                }
            }

            default:
                return NextResponse.json({ status: 400, error: "Invalid action" });
        }
    } catch (error) {
        console.error(error);
        return NextResponse.json({
            status: 500,
            error: "Failed to process request",
        });
    }
}
